import React, { useState, useEffect } from 'react';
import { Modal, Row, Col, Card, Statistic, Progress, Table, message } from 'antd';
import { CheckCircleOutlined, TeamOutlined, ClockCircleOutlined } from '@ant-design/icons';
import axios from 'axios';

const SignInStatistics = ({ taskId, visible, onClose }) => {
  const [stats, setStats] = useState({
    totalStudents: 0,
    signedIn: 0,
    absent: 0,
    signInRate: 0,
    classStats: []
  });
  const [loading, setLoading] = useState(false);
  const [taskInfo, setTaskInfo] = useState(null);

  // 获取签到统计数据
  const fetchStatistics = async () => {
    if (!taskId) return;
    
    setLoading(true);
    try {
      const response = await axios.get(`/teacher/sign_in/statistics?task_id=${taskId}`);
      if (response.data && (response.data.code === 2000 || response.data.code === 0)) {
        const data = response.data.data || {};
        setStats({
          totalStudents: data.total_students || 0,
          signedIn: data.signed_in || 0,
          absent: data.absent || 0,
          signInRate: data.sign_in_rate || 0,
          classStats: data.class_stats || []
        });
        setTaskInfo(data.task || {});
      } else {
        message.error('获取签到统计数据失败');
      }
    } catch (error) {
      console.error('获取签到统计数据出错:', error);
      message.error('获取签到统计数据出错，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 当模态框可见或任务ID变化时获取数据
  useEffect(() => {
    if (visible && taskId) {
      fetchStatistics();
    }
  }, [visible, taskId]);

  // 班级统计表格列定义
  const columns = [
    {
      title: '班级',
      dataIndex: 'class_name',
      key: 'class_name',
    },
    {
      title: '总人数',
      dataIndex: 'total',
      key: 'total',
    },
    {
      title: '已签到',
      dataIndex: 'signed_in',
      key: 'signed_in',
    },
    {
      title: '未签到',
      dataIndex: 'absent',
      key: 'absent',
    },
    {
      title: '签到率',
      key: 'sign_in_rate',
      render: (_, record) => (
        <Progress 
          percent={parseFloat(record.sign_in_rate).toFixed(1)} 
          size="small" 
          status={record.sign_in_rate >= 80 ? "success" : "normal"}
        />
      ),
    },
  ];

  return (
    <Modal
      title={`签到任务: ${taskInfo?.description || ''} - 统计数据`}
      open={visible}
      onCancel={onClose}
      width={800}
      footer={null}
    >
      <div style={{ marginBottom: 24 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Card>
              <Statistic
                title="总人数"
                value={stats.totalStudents}
                prefix={<TeamOutlined />}
                loading={loading}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="已签到"
                value={stats.signedIn}
                valueStyle={{ color: '#3f8600' }}
                prefix={<CheckCircleOutlined />}
                loading={loading}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="未签到"
                value={stats.absent}
                valueStyle={{ color: '#cf1322' }}
                prefix={<ClockCircleOutlined />}
                loading={loading}
              />
            </Card>
          </Col>
        </Row>
      </div>

      <div style={{ marginBottom: 24 }}>
        <Card title="总体签到率">
          <Progress
            percent={parseFloat(stats.signInRate).toFixed(1)}
            status={stats.signInRate >= 80 ? "success" : "normal"}
          />
        </Card>
      </div>

      <Card title="班级签到统计">
        <Table 
          columns={columns}
          dataSource={stats.classStats}
          rowKey="class_id"
          loading={loading}
          pagination={false}
          locale={{ emptyText: '暂无班级数据' }}
        />
      </Card>
    </Modal>
  );
};

export default SignInStatistics; 